/**
 * 入库管理模块
 * Created by zengtao on 2017/8/28.
 */
define(["jquery", "artTemplate","common","./search_rk_list","./search_rkth_list", "text!../../tpls/rukuguanli/rukuguanlimain.html",
        "text!../../tpls/rukuguanli/addruku.html","text!../../tpls/rukuguanli/addtuihuo.html",
        "text!../../tpls/rukuguanli/ruku_tuihuo.html"], function ($, art,common,search_rk_list,search_rkth_list, rukuguanlimain,addruku,addtuihuo,ruku_tuihuo) {
	var url = common.kcUrl(); 
	return function () {
		$("#mainpage").empty().append(rukuguanlimain);
		init_datetimepicker_ymd();
		search_rk_list(common.monthnow());
		
		//1.0	时间发生改变时请求入库列表数据
		$("#search_ruku_lists").on("change",".form_datetime",function(){
			var startDate = $("#ruku_begin_date_ipt").val();
			var endDate = $("#ruku_end_date_ipt").val();
			var keyWord = $("#ruku_keyword_ipt").val() || "";
			search_rk_list(startDate,endDate,keyWord);
		});
		
		//1.1	输入关键字回车后请求入库列表数据
		 $('#ruku_keyword_ipt').off("keypress").on("keypress",function(event){  
            if(event.keyCode == "13"){ 
            	var startDate = $("#ruku_begin_date_ipt").val();
    			var endDate = $("#ruku_end_date_ipt").val();
    			var keyWord = $("#ruku_keyword_ipt").val() || "";
    			search_rk_list(startDate,endDate,keyWord);  
            }  
        });
		
		
		//新增按钮导入入库操作页面
		$("#rkglAddRkBtn").on("click",function(){
			var navMenu = '<li >首页</li>'+
			'<li onclick=toRukuPage()>入库管理</li>'+
	        '<li class="active">入库</li>';
			$("#nav-top").empty().append(navMenu);
			$("#mainpage").empty();
			$("#mainpage").append(addruku);
			$("#rkgl_rklb_ul_svb").empty();
			$("#rkgl_rklb_ul_svb").append($($("#tpl_add_ruku_row").html()));
			init_datetimepicker_ymd();
			common.cloneOp("#sk_operator_id");//添加操作人选项
			
			//用来显示提示物品内容的ul
			var searchTplHtml = '<ul id="searchresult" style="position:absolute;top:34px;z-index:998;width:212px;border:1px solid #ccc;border-top:none;max-height:240px;overflow-y:auto;overflow-x:hidden;text-align:left;"></ul>';
			var $searchTplHtml = $(searchTplHtml);
			
			var searchTplHtml2 = '<ul id="searchresult2" style="position:absolute;top:34px;z-index:998;width:212px;border:1px solid #ccc;border-top:none;max-height:240px;overflow-y:auto;overflow-x:hidden;text-align:left;"></ul>';
			var $searchTplHtml2 = $(searchTplHtml2);
			
			// 新增入库 - 
			// 输入框获取焦点时显示所有物品类型信息
			$("#rkgl_rklb_ul_svb").off("focus").on("focus",".searchByType",function(){
				$_that = $(this);
				$.get(url + "inventory/inventorytypeList.shtml",function(res){
					console.log(res);
					if(res.status == 1){
						layer.msg("网络忙,请稍后重试");
						return
					}
				    var result = eval('(' + res.result + ')');
				    var wplxListHtml = art.render($("#tpl_add_search_type_row").html(), {
				        result: result   
				    });
				   
				    var $wplxListHtml = $(wplxListHtml);
				    $_that.parent().append($searchTplHtml);//添加提示类型的容器
				    $("#searchresult").empty().append($wplxListHtml);//添加提示的物品类型内容
				    $("#searchresult li").on("click.copytext",function(){
				    	$(this).parent().parent().children("input").val($(this).data("sk_type_name"));
				    	var sk_type_id = $(this).data("sk_type_id");
				    	var $_that = $(this);
				    	
				    	// 请求物品类型下的物品信息
						$.get(url + "inventory/inventoryList.shtml?type="+sk_type_id,function(res){
							console.log(res);
							if(res.status == 1){
								layer.msg("网络忙,请稍后重试");
								return
							}
						    var result = eval('(' + res.result + ')');
						    var wplxListHtml = art.render($("#tpl_search_type_info").html(), {
						        result: result   
						    });
						   
						    var $wplxListHtml = $(wplxListHtml);
						    $_that.parent().parent().siblings(".rkgl_rk_ggmc").append($searchTplHtml2);//添加物品名称提示的容器
						    $("#searchresult2").empty().append($wplxListHtml);
						    
						    // 物品名称的每行
						    $("#searchresult2 li").on("click.copytext",function(){
						    	$(this).parent().parent().children("input").val($(this).data("sk_type_name"));//物品名称
						    	$(this).parent().parent().children("input").data("sk_inventory_id",$(this).data("sk_inventory_id"));//物品ID
						    	$(this).parent().parent().siblings(".rkgl_rk_sccj").children("input").val($(this).data("sk_facturers_name"));
						    	$(this).parent().parent().siblings(".rkgl_rk_gys").children("input").val($(this).data("sk_dealer_name"));
						    	$(this).parent().parent().siblings(".rkgl_rk_wpdj").children("input").val($(this).data("sk_inventory_price_in"));//入库价格
						    	$("#searchresult2").remove();
						    });
						});
				    	
				    });
				    
				})
			});
			
			// 物品类型输入框失去焦点时移除提示框
			$("#rkgl_rklb_ul_svb").on("blur",".searchByType",function(){
		    	setTimeout(function() {
		    		$("#searchresult").remove();  
		        }, 200);
		    	
		    });
			
			// 输入物品类型提示信息
			$("#rkgl_rklb_ul_svb").off("keyup.searchByType").on("keyup.searchByType",".searchByType",function(){
				var keyword = $(this).val();
				$(this).parent().siblings().children("input").val("");
				
				$_that = $(this);
				$.post(url + "inventory/autoinventoryList.shtml",{name:keyword,type:2},function(res){
					var result = eval('(' + res.result + ')');
					if(result.length == 0){
						$("#searchresult").empty().append("<li>无此类型<li>");
						return
					}
				    var wplxListHtml = art.render($("#tpl_add_search_row").html(), {
				        result: result   
				    });				   
				    var $wplxListHtml = $(wplxListHtml);
				    $_that.parent().append($searchTplHtml);
				    $("#searchresult").empty().append($wplxListHtml);
				   
				    $("#searchresult li").hover(function(){
				        $(this).css("background-color","#F8F8F8");
				    },function(){
				        $(this).css("background-color","#fff");
				    });
				    $("#searchresult li").on("click.copytext",function(){
				    	$(this).parent().parent().children("input").val($(this).data("inventory_id"));
				    	$(this).parent().parent().siblings(".rkgl_rk_ggmc").children("input").val($(this).data("inventory_name"));
				    	$(this).parent().parent().siblings(".rkgl_rk_sccj").children("input").val($(this).data("facturers_name"));
				    	$(this).parent().parent().siblings(".rkgl_rk_gys").children("input").val($(this).data("dealer_name"));
				    	$(this).parent().parent().siblings(".rkgl_rk_wpdj").children("input").val($(this).data("inventory_price_in"));
				    	$(this).parent("#searchresult").remove();
				    });
				    $("#rkgl_rklb_ul_svb").on("blur",".searchById",function(){
				    	setTimeout(function() {
				    		$("#searchresult").remove();  
				        }, 200);
				    	
				    });
				});
			});
			
			//新增入库 - 输入规格名称查询提示信息
			$("#rkgl_rklb_ul_svb").off("keyup.byname").on("keyup.byname",".searchByName",function(){
				var keyword = $(this).val();
				$(this).parent().siblings().children("input").val("");
				if(!keyword){
					$("#searchresult").remove();
					return
				}
				$_that = $(this);
				$.post(url + "inventory/autoinventoryList.shtml",{name:keyword,type:1},function(res){
					var result = eval('(' + res.result + ')');
					if(result.length == 0){
						$("#searchresult").remove();
						return
					}
				    var wplxListHtml = art.render($("#tpl_add_searchname_row").html(), {
				        result: result   
				    });				   
				    var $wplxListHtml = $(wplxListHtml);
				    $_that.parent().append($searchTplHtml);
				    $("#searchresult").empty().append($wplxListHtml);
				    
				    $("#searchresult li").hover(function(){
				        $(this).css("background-color","#F8F8F8");
				    },function(){
				        $(this).css("background-color","#fff");
				    });
				    $("#searchresult li").on("click",function(){
				    	$(this).parent().parent().siblings(".rkgl_rk_wpbm").children("input").val($(this).data("inventory_id"));
				    	$(this).parent().parent().children("input").val($(this).data("inventory_name"));
				    	$(this).parent().parent().siblings(".rkgl_rk_sccj").children("input").val($(this).data("facturers_name"));
				    	$(this).parent().parent().siblings(".rkgl_rk_gys").children("input").val($(this).data("dealer_name"));
				    	$(this).parent().parent().siblings(".rkgl_rk_wpdj").children("input").val($(this).data("inventory_price_in"));
				    	$(this).parent("#searchresult").remove();
				    });
				});
				$("#rkgl_rklb_ul_svb").on("blur",".searchByName",function(){
			    	setTimeout(function() {
			    		$("#searchresult").remove();  
			        }, 200);
			    	
			    });
			});
			
			//计算入库每行的总金额
			$("#rkgl_rklb_ul_svb").off("keyup.count").on("keyup.count",".sk_in_operation_num",function(){
				var count = parseInt($(this).val());
				var price = parseFloat($(this).parent().siblings(".rkgl_rk_wpdj").children("input").val());
				if(isNaN(count) || isNaN(price)){
					return
				}
				$(this).parent().siblings(".rkgl_rk_wpzj").children("input").val(common.float_num2(count*price));
			});	
			$("#rkgl_rklb_ul_svb").off("keyup.price").on("keyup.price",".sk_in_price",function(){
				var count = parseInt($(this).parent().siblings(".rkgl_rk_rksl").children("input").val());
				var price = parseFloat($(this).val());
				if(isNaN(count) || isNaN(price)){
					return
				}
				//$(this).parent().siblings(".rkgl_rk_wpzj").children("input").val(Math.round(count*price*1000)/1000);
				$(this).parent().siblings(".rkgl_rk_wpzj").children("input").val(common.float_num2(count*price));
			});	
			//增加一行
			$("#mainpage").off("click.addrow").on("click.addrow",".add_row_ctrl",function(){
				var $addRow = $($("#tpl_add_ruku_row").html());
				var lastXh = $("#rkgl_rklb_ul_svb .list_jl_view_1503:last").children(".rkgl_rk_xh").text() || 0;
				//新增的序号递增1，加入到ul末尾
				$addRow.find(".rkgl_rk_xh").text(parseInt(lastXh) + 1);							
				$("#rkgl_rklb_ul_svb").append($addRow);
				init_datetimepicker_ymd();
				if($("#rkgl_rklb_ul_svb")[0].scrollHeight>$("#rkgl_rklb_ul_svb")[0].clientHeight||$("#rkgl_rklb_ul_svb")[0].offsetHeight>$("#rkgl_rklb_ul_svb")[0].clientHeight){ 
					$(".title-pr").css("padding-right","17px");
				} 
			});
			//删除一行
			$("#mainpage").off("click.delrow").on("click.delrow",".con_row_ctrl",function(){
				if($(this).parent().siblings(".rkgl_rk_xh").text() == 1){
					return
				}
				//改变删除行之后的每行序号
				$(this).parent().parent().nextAll().find(".rkgl_rk_xh").each(function(){
					var count = parseInt($(this).text());
					$(this).text(count - 1);
				});
				$(this).parent().parent().remove();//删除自己所在的行
			});
			
			//入库管理 - 新增入库 - 提交
			$("#saveAddBtn").on("click",function(){
				var sendData = [];
				var flag = true;
				$("#rkgl_rklb_ul_svb > li").each(function(v,i){
					var sk_in_inventory_id = $(this).find(".searchByName").data("sk_inventory_id");
					var sk_in_inventory_name = $(this).find(".searchByName").val(); //'物品名称'
					var sk_in_batch = $(this).find(".sk_in_batch").val();
					var sk_in_price = common.float_num2(($(this).find(".sk_in_price").val()));
					var sk_in_operation_type = 0;
					var sk_in_operation_num = $(this).find(".sk_in_operation_num").val();
					var sk_in_operator = $("#sk_operator_id").val();
					var sk_in_date = $("#sk_in_date").val();
					var sk_product_date = $(this).find(".sk_product_date").val() || "";
					var sk_valid_date = $(this).find(".sk_valid_date").val();
					var sk_notes = $("#sk_notes").val();
					if(!sk_in_inventory_id || !sk_in_batch || !sk_in_price || !sk_in_operation_num  || !sk_valid_date || !sk_in_inventory_name){
		            	var $_this = $(this);
		            	warnMsg3($_this,".inline-ipt-focus","带 * 项为必填项");
		            	flag = false;
		            	return false;
		            }
					var list_obj = {
						  sk_in_inventory_id:sk_in_inventory_id,
				          sk_in_batch:sk_in_batch,
				          sk_in_price:sk_in_price,
				          sk_in_operation_type:sk_in_operation_type,
				          sk_in_operation_num:sk_in_operation_num,
				          sk_in_operator:sk_in_operator,
				          sk_in_date:sk_in_date,
				          sk_product_date:sk_product_date,
				          sk_valid_date:sk_valid_date,
				          sk_notes:sk_notes	
					};
					sendData.push(list_obj);
				});
				if(!flag){
					return
				}
				//console.log(sendData);
				var index = layer.load(2, {time: 5*1000});
				$(this).prop('disabled', true).addClass("waiting");
				var $_that = $(this);
				$.ajax({
					url: url + "stock/insertInstock.shtml" ,
					type: "POST",
					async:false,
					data:{inarray:JSON.stringify(sendData)},
					success: function(res){
						layer.close(index);
						$_that.prop('disabled', false).removeClass("waiting");
						if(res.status == 1){
		            		layer.msg("网络忙,请稍后重试");
		            		return
		            	}
		        		layer.msg("入库成功");
		        		$("#rkgl_rklb_ul_svb > li").find("input").val('');
		        		$("#sk_notes").val("");
					}
				});
				//$("#kc_rukugl_a").trigger("click");
			});
			
			//入库管理 - 新增入库 - 取消
			$("#cancelAddBtn").on("click",function(){
				var flag = true;
				$("#rkgl_rklb_ul_svb input").each(function(){
					if($(this).val()){
						flag = false;
						return false;
					}
				});
				if(flag){
	            	$("#kc_rukugl_a").trigger("click");
	        	}
				$("#rkgl_rklb_ul_svb").find("input").val("");
			});
			
		});

		//2.1	入库退货按钮跳转退货操作页面
		$("#rkglAddThBtn").on("click",function(){
			var sk_in_id_array = [];
			$("#rkgl_wpxxlist_ul_svb > li").find("input[name='out_checkbox']").each(function(i,v){
				if($(this).is(':checked')){
					sk_in_id_array.push($(this).siblings(".sk_in_inventory_id").data("inid").toString());
				}
				
			});
			if(sk_in_id_array.length == 0){
				layer.msg("请选择需要退货的物品");
				return
			}
			var navMenu = '<li style="padding:0 6px;">首页</li>'+
			'<li style="padding:0 6px;" onclick=toRukuPage()>入库管理</li>'+
			'<li style="padding:0 6px;" class="active">退货</li>';
			$("#nav-top").empty().append(navMenu);
			$("#mainpage").empty().append(addtuihuo);
			init_datetimepicker_ymd();
			//console.log(sk_in_id_array);
			common.cloneOp("#sk_operator_id2");//添加操作人选项
			
			$.ajax({
				url: url + "stock/instockListByarray.shtml",
				type: "POST",
				data:{
					array:sk_in_id_array,
				},
				traditional :true,
				success: function(res){
					var result = eval('(' + res.result + ')');
					var rkList = art.render($("#tpl_add_tuihuolist").html(), {
						result: result   
					});					
					var $rkList = $(rkList);
					$("#rkgl_addrkth_ul_svb").append($rkList);
					setPaddingR("#rkgl_addrkth_ul_svb",".title-pr",410);
					//显示和隐藏操作按钮
				    $("#rkgl_addrkth_ul_svb > li").hover(function(){
				    	$(this).children(".jbxx_wplx_cz").addClass("opacity_ctrl");
				    	$(this).children(".jbxx_wplx_cz").removeClass("opacity_noctrl");
				    },function(){
				    	$(this).children(".jbxx_wplx_cz").addClass("opacity_noctrl");
						$(this).children(".jbxx_wplx_cz").removeClass("opacity_ctrl");
				    });
				    
				    //入库退货列表 - 删除不需要退货的行
					$(".delete_img").on("click",function(){
						var $_that = $(this);
					    layer.confirm('确认删除？', {
					      icon: 3,
					      title: '提示'
					    }, function (index) {
					  	//改变删除行之后的每行序号
					      $_that.parent().parent().nextAll().find(".rkgl_addrkth_xh").each(function(){
								var count = parseInt($(this).text());
								$(this).text(count - 1);
							});
					      $_that.parent().parent().remove();//删除自己所在的行
					      layer.close(index);
					    });
					});
					
					//计算入库退货每行的总金额
					$("#rkgl_addrkth_ul_svb").off("keyup.count").on("keyup.count",".out_count",function(){
						var count = parseInt($(this).val());
						var price = parseFloat($(this).parent().siblings(".rkgl_addrkth_rkdj").text());
						if(isNaN(count) || isNaN(price)){
							$(this).parent().siblings(".rkgl_addrkth_thjg").text("");
							return
						}
						$(this).parent().siblings(".rkgl_addrkth_thjg").text(common.float_num2(count*price));
					});	
					
					//入库管理 - 新增入库退货 - 提交
					$("#saveAddBtn").on("click",function(){
						var sendData = [];
						var flag = true;
						
						$("#rkgl_addrkth_ul_svb > li").each(function(v,i){
							var sk_in_id = $(this).data("skinid"); //'ID'
							var sk_in_inventory_id = $(this).find(".rkgl_addrkth_wpbm").text();
							var sk_in_num = parseInt($(this).find(".rkgl_addrkth_kcsl").text());
							var sk_in_operation_num = parseInt($(this).find(".rkgl_addrkth_thsl").children("input").val());
							var sk_in_operator = $("#sk_operator_id2").val();
							var sk_in_date = $("#sk_in_date").val();
							var sk_notes = $("#sk_notes").val();
							if(!sk_in_operation_num){
				            	var $_this = $(this);
				            	warnMsg3($_this,".inline-ipt-focus","请填写退货数量");
				            	flag = false;
				            	return false;
				            }
							if(sk_in_operation_num > sk_in_num){
				            	var $_this = $(this);
				            	warnMsg3($_this,".inline-ipt-focus","退货数量大于入库数量");
				            	flag = false;
				            	return false;
				            }
							var list_obj = {
								  sk_in_id:sk_in_id,
								  sk_in_inventory_id:sk_in_inventory_id,
						          sk_in_operation_num:sk_in_operation_num,
						          sk_in_operator:sk_in_operator,
						          sk_in_date:sk_in_date,
						          sk_notes:sk_notes	
							};
							sendData.push(list_obj);
						});
						if(!flag){
							return
						}
						//console.log(sendData);
						var index = layer.load(2, {time: 5*1000});
						$(this).prop('disabled', true).addClass("waiting");
						var $_that = $(this);
						$.ajax({
							url: url + "stock/insertInstockback.shtml" ,
							type: "POST",
							async:false,
							data:{inarray:JSON.stringify(sendData)},
							success: function(res){
								layer.close(index);
								$_that.prop('disabled', false).removeClass("waiting");
								if(res.status == 1){
				            		layer.msg("网络忙,请稍后重试");
				            		return
				            	}
				        		layer.msg("退货成功");
				        		$("#rkgl_addrkth_ul_svb > li").find("input").val('');
				        		$("#rkgl_addrkth_ul_svb > li").find("span").text('');
				        		$("#sk_notes").val("");
				        		$("#kc_rukugl_a").trigger("click");
							}
						});
						
					});
					
					//入库管理 - 新增入库退货 - 取消
					$("#cancelAddBtn").on("click",function(){
						 $("#kc_rukugl_a").trigger("click");
					});
				}
			});
		});

		//3.1  退货记录按钮导入退库记录列表页面
		$("#rkglThjlBtn").on("click",function(){
			var navMenu = '<li style="padding:0 6px;">首页</li>'+
			'<li style="padding:0 6px;" onclick=toRukuPage()>入库管理</li>'+
			'<li style="padding:0 6px;" class="active">入库退货记录</li>';
			$("#nav-top").empty().append(navMenu);
			$("#mainpage").empty().append(ruku_tuihuo);
			init_datetimepicker_ymd();
			search_rkth_list(common.monthnow());//默认请求最近一个月的数据
			
			//3.11	时间发生改变时请求数据
			$("#search_ruku_lists").on("change",".form_datetime",function(){
				var startDate = $("#ruku_begin_date_ipt").val();
				var endDate = $("#ruku_end_date_ipt").val();
				var keyWord = $("#ruku_keyword_ipt").val() || "";
				search_rkth_list(startDate,endDate,keyWord);//查询数据并显示 
			});
			//3.12	输入关键字回车后请求数据
			 $('#search_ruku_lists').on("keypress","#ruku_keyword_ipt",function(event){  
	            if(event.keyCode == "13"){ 
	            	var startDate = $("#ruku_begin_date_ipt").val();
	    			var endDate = $("#ruku_end_date_ipt").val();
	    			var keyWord = $("#ruku_keyword_ipt").val() || "";
	    			search_rkth_list(startDate,endDate,keyWord); //查询数据并显示 
	            }  
	        });
		});
		
		//4.1 打印入库记录功能   
		$("#dyrkdBtn").on("click",function(){
			var sk_in_bill,sk_time;
			var sel_sk_in_bill = $('#rkgl_rklist_ul_svb .list_jl_view_1503').each(function(v,i){
				if($(this).hasClass("list_active")){
					sk_in_bill = $(this).find(".sk_in_bill_ipt").val();
					sk_time = $(this).find(".rkgl_rkjl_rksj input").val();
					return sk_in_bill,sk_time;
				}
			});
			var getDataBegin = layer.load(4, {time: 6*1000});
			$.ajax({
				type: "GET",
				url: url + "stock/instockList.shtml?bill="+sk_in_bill,
				success: function(res){
					layer.close(getDataBegin);
					var result = eval('(' + res.result + ')');
					console.log(result);
					var rkList = art.render($("#tpl_print_sk_in_bill").html(), {
						result: result   
					});
					var winname = window.open('', "_blank",'');
				    winname.document.body.innerHTML = rkList;
				    winname.print(); 
				}
			});
		});
	};
});